/*
 * Created on 15-Apr-2006
 * Actualis Center
 *
 */
package org.bookie.framework.services.impl;

import java.io.IOException;
import java.io.PrintWriter;

import org.apache.tapestry.IMarkupWriter;
import org.apache.tapestry.IPage;
import org.apache.tapestry.IRequestCycle;
import org.apache.tapestry.markup.MarkupWriterSource;
import org.apache.tapestry.services.Infrastructure;
import org.apache.tapestry.services.RequestLocaleManager;
import org.apache.tapestry.services.impl.DefaultResponseBuilder;
import org.apache.tapestry.util.ContentType;
import org.bookie.framework.services.EmailResponseRenderer;

public class EmailResponseRendererImpl implements EmailResponseRenderer {

	private RequestLocaleManager _localeManager;

	private PrintWriter _writer;

	private MarkupWriterSource _markupWriterSource;

	private Infrastructure _infrastructure;

	/**
	 * Inside a {@link org.apache.tapestry.util.ContentType}, the output
	 * encoding is called "charset".
	 */

	public static final String ENCODING_KEY = "charset";

	/*
	 * (non-Javadoc)
	 * 
	 * @see actualis.web.tapestry.framework.EmailResponseRenderer#renderResponse(org.apache.tapestry.IRequestCycle)
	 */
	public String renderResponse(IRequestCycle cycle, boolean html)
			throws IOException {
		_localeManager.persistLocale();

		IPage page = cycle.getPage();

		ContentType contentType = page.getResponseContentType();

		String encoding = contentType.getParameter(ENCODING_KEY);

		if (encoding == null) {
			encoding = _infrastructure.getOutputEncoding();

			contentType.setParameter(ENCODING_KEY, encoding);
		}

		IMarkupWriter _markupWriter = null;

		if (html) {
			_markupWriter = _markupWriterSource.newMarkupWriter(_writer,
					contentType);
		} else {
			_markupWriter = new TextWriter(_writer);
		}

		DefaultResponseBuilder defaultResponseBuilder = new DefaultResponseBuilder(_markupWriter);
		cycle.setResponseBuilder(defaultResponseBuilder);
		cycle.renderPage(defaultResponseBuilder);

		_markupWriter.close();

		return encoding;
	}

	public void setLocaleManager(RequestLocaleManager localeManager) {
		_localeManager = localeManager;
	}

	public final void setWriter(PrintWriter writer) {
		_writer = writer;
	}

	public final void setMarkupWriterSource(
			MarkupWriterSource markupWriterSource) {
		_markupWriterSource = markupWriterSource;
	}

	public final void setInfrastructure(Infrastructure infrastructure) {
		_infrastructure = infrastructure;
	}

}
